import {
	app,
	Menu,
	ipcMain,
	globalShortcut,
	BrowserWindow
} from 'electron'
import {
	autoUpdater
} from "electron-updater"
// 关闭自动下载
autoUpdater.autoDownload = false

// import fs from 'fs';
import path from 'path';
// import {registerMenu}  from './menu'
var uploadUrl = "http://1.116.132.63/sup/";
// var extensions = [];

// var extensionsDir = './extensions';
// if (fs.existsSync(extensionsDir) &&
// 	fs.statSync(extensionsDir).isDirectory()) {
// 	readDirSync(extensionsDir);
// } else {
// 	fs.mkdir(extensionsDir);
// }

// function readDirSync(pathStr) {
// 	var pa = fs.readdirSync(pathStr);
// 	pa.forEach(function(ele, index) {
// 		var info = fs.statSync(pathStr + "/" + ele)
// 		if (info.isDirectory()) {
// 			var extensionPath = path.join(pathStr, ele)
// 			extensions.push(extensionPath);
// 		}
// 	})
// }

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
	global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
}

let mainWindow
const winURL = process.env.NODE_ENV === 'development' ?
	`http://localhost:9080` :
	`file://${__dirname}/index.html`


// 检测更新，在你想要检查更新的时候执行，renderer事件触发后的操作自行编写
function updateHandle() {
	let message = {
		error: '检查更新出错',
		checking: '正在检查更新……',
		updateAva: '检测到新版本',
		updateNotAva: '当前使用已是最新版本',
	};

	autoUpdater.setFeedURL(uploadUrl);
	autoUpdater.on('error', function(error) {
		sendUpdateMessage(JSON.stringify({
			"msg": message.error,
			"err": error
		}))
	});
	autoUpdater.on('checking-for-update', function() {
		sendUpdateMessage(message.checking)
	});
	
	autoUpdater.on('update-available', function(info) {
		mainWindow.webContents.send('updateAva', info)
	});
	
	autoUpdater.on('update-not-available', function(info) {
		sendUpdateMessage({
			msg: message.updateNotAva,
			info
		})
	});

	// 更新下载进度事件
	autoUpdater.on('download-progress', function(progressObj) {
		mainWindow.webContents.send('downloadProgress', progressObj);
	})

	autoUpdater.on('update-downloaded', function(event, releaseNotes, releaseName, releaseDate, updateUrl,
		quitAndUpdate) {

		autoUpdater.quitAndInstall();
		// ipcMain.on('updateNow', (e, arg) => {
		// 	//some code here to handle event

		// });

		// mainWindow.webContents.send('isUpdateNow', JSON.stringify({
		// 	releaseNotes,
		// 	releaseName,
		// 	releaseDate,
		// 	updateUrl,
		// 	quitAndUpdate
		// }));
	});

	ipcMain.on("checkForUpdate", () => {
		//执行自动更新检查
		autoUpdater.checkForUpdates();
	})

	ipcMain.on('downloadUpdate', () => {
		// 下载
		// log.warn('执行下载')
		autoUpdater.downloadUpdate()
	})
}

// 通过main进程发送事件给renderer进程，提示更新信息
function sendUpdateMessage(text) {
	mainWindow.webContents.send('message', text)
}

function createWindow() {
	// 隐藏菜单
	Menu.setApplicationMenu(null)

	/**
	 * Initial window options
	 */
	mainWindow = new BrowserWindow({
		height: 1000,
		useContentSize: true,
		width: 1500,
		// webPreferences: {
		// 	nodeIntegration: true,
		// },
		// fullscreen: true
	})

	// registerMenu(mainWindow)

	mainWindow.loadURL(winURL)

	// 加入vue插件
	// extensions.forEach((extensionPath) => {
	// 	BrowserWindow.addExtension(extensionPath);
	// });


	// 设置快捷键
	var shortcutList = [];
	shortcutList.push('CommandOrControl+H')
	shortcutList.push('CommandOrControl+Left')
	shortcutList.push('CommandOrControl+Right')
	shortcutList.push('CommandOrControl+Up')
	shortcutList.push('CommandOrControl+Down')
	shortcutList.push('CommandOrControl+G')
	shortcutList.push('CommandOrControl+L')
	shortcutList.push('CommandOrControl+F12')
	shortcutList.push('F5')
	shortcutList.push('ESC')

	shortcutList.forEach((shortcut) => {
		globalShortcut.register(shortcut, () => {
			mainWindow.webContents.send("shortcut-func", shortcut);
		});
	})


	globalShortcut.register('CommandOrControl+Shift+I', () => {
		mainWindow.webContents.openDevTools();
	});

	globalShortcut.register('CommandOrControl+Shift+L', () => {
		mainWindow.webContents.send("log", BrowserWindow.getDevToolsExtensions());
	});

	mainWindow.on('closed', () => {
		mainWindow = null
	})

	updateHandle();
}

app.on('ready', createWindow)


app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

app.on('will-quit', () => {
	globalShortcut.unregisterAll();
})

app.on('activate', () => {
	if (mainWindow === null) {
		createWindow()
	}
});




/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
